package com.ruoyi.web.controller.smy;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.LinkUrl;
import com.ruoyi.common.constant.UserType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.smy.MallMerchantPersonalInfo;
import com.ruoyi.common.core.domain.smy.SecurityWebUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.dto.OptDto;
import com.ruoyi.common.dto.ResponseDto;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.smy.IMallMerchantPersonalInfoService;
import com.ruoyi.system.service.smy.ISecurityWebUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/smy/merchant")
public class SecurityWebUserController extends BaseController {

	@Resource
	private ISecurityWebUserService securityWebUserService;

	@Resource
	private IMallMerchantPersonalInfoService merchantPersonalInfoService;

	@Resource
	private ISysRoleService roleService;

	@Value("${app.baseUrl}")
	private String appBaseUrl;

	@PreAuthorize("@ss.hasPermi('smy:merchant:list')")
	@GetMapping("/list")
	public TableDataInfo list(SecurityWebUser securityWebUser) {
		SysUser user = SecurityUtils.getLoginUser().getUser();
		if(roleService.checkHaveRole(user.getRoles(), UserType.QYJMS)){
			if(StrUtil.isNotEmpty(user.getProvinceName())){
				securityWebUser.setProvinceName(user.getProvinceName());
			}
			if(StrUtil.isNotEmpty(user.getCityName()) && !StrUtil.equals("全部",user.getCityName())){
				securityWebUser.setCityName(user.getCityName());
			}
			if(StrUtil.isNotEmpty(user.getCountyName()) && !StrUtil.equals("全部",user.getCountyName())){
				securityWebUser.setCountyName(user.getCountyName());
			}
		}
		startPage();
		//查询所有商家信息
		securityWebUser.setRoleId(4L);
		List<SecurityWebUser> list = securityWebUserService.selectSecurityWebUserList(securityWebUser);
		return getDataTable(list);
	}

	@PreAuthorize("@ss.hasPermi('smy:user:export')")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, SecurityWebUser securityWebUser) {
		List<SecurityWebUser> list = securityWebUserService.selectSecurityWebUserList(securityWebUser);
		ExcelUtil<SecurityWebUser> util = new ExcelUtil<SecurityWebUser>(SecurityWebUser.class);
		util.exportExcel(response, list, "【请填写功能名称】数据");
	}

	@PreAuthorize("@ss.hasPermi('smy:merchant:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(securityWebUserService.selectMerchantWithPersonalInfo(id));
	}

	@PreAuthorize("@ss.hasPermi('smy:merchant:add')")
	@Log(title = "新增商家用户", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody SecurityWebUser securityWebUser) {
		try {
			//校验商家账户在系统中不存在
			checkWebUserInfo(securityWebUser);
			//1.在APP平台创建商家账户
			Map<String,Object> paoTuiShopUser = new HashMap<>(2);
			paoTuiShopUser.put("userPhone",String.valueOf(securityWebUser.getMobile()));
			paoTuiShopUser.put("userNickName",String.valueOf(securityWebUser.getRealname()));
			System.out.println(appBaseUrl+ LinkUrl.CREATE_COOKER_URL);
			String responseStr = HttpRequest.post(appBaseUrl+ LinkUrl.CREATE_COOKER_URL).body(JSONUtil.toJsonStr(paoTuiShopUser)).execute().body();
			System.out.println(responseStr);
			ResponseDto responseDto = JSONUtil.toBean(responseStr,ResponseDto.class);
			if(responseDto.isHasError()){
				throw new RuntimeException(responseDto.getMessage());
			}
			MallMerchantPersonalInfo mallMerchantPersonalInfo = new MallMerchantPersonalInfo();
			mallMerchantPersonalInfo.setCookername(securityWebUser.getRealname());
			merchantPersonalInfoService.insertMallMerchantPersonalInfo(mallMerchantPersonalInfo);
			logger.info(mallMerchantPersonalInfo.toString());

			//保存商家信息：设置默认值
			//设置默认启用
			securityWebUser.setAccountnonlocked(0);
			String userNo = IdUtil.simpleUUID();
			securityWebUser.setUserno(userNo);
			securityWebUser.setRoleId(4L);
			securityWebUser.setCreateTime(new Date());
			securityWebUser.setCreatetime(new Date());
			securityWebUser.setMerchantentertime(new Date());
			securityWebUser.setRealname(securityWebUser.getRealname());
			securityWebUser.setMerchantcheckstatus(1L);
			securityWebUser.setGoodsnumber(0L);
			securityWebUser.setTotalorderamount(0L);
			securityWebUser.setTotalordernumber(0L);
			securityWebUser.setSex(0L);
			securityWebUser.setSelfsupport(0L);
			securityWebUser.setFirstlogin(0);
			securityWebUser.setMerchantinvoicetitletype(0L);
			securityWebUser.setLivebalance(0.00d);
			securityWebUser.setLivetype(0L);
			securityWebUser.setLivestatus(0);
			securityWebUser.setBalance(0.00d);
			securityWebUser.setOrdermessagenumber(0L);
			securityWebUser.setSystemmessagenumber(0L);
			securityWebUser.setWithdrawmessagenumber(0L);
			//设置商家用户身份为个人
			securityWebUser.setMaintype(3L);
			securityWebUser.setMerchantpersonalinfoId(mallMerchantPersonalInfo.getId());
			//设置默认评分都为5分
			securityWebUser.setTasteratestar(RandomUtil.randomDouble(4.0d,5.0d,2, RoundingMode.DOWN));
			securityWebUser.setLookratestar(RandomUtil.randomDouble(4.0d,5.0d,2, RoundingMode.DOWN));
			securityWebUser.setAttituderatestar(RandomUtil.randomDouble(4.0d,5.0d,2, RoundingMode.DOWN));
			securityWebUser.setRatestar(RandomUtil.randomDouble(4.0d,5.0d,2, RoundingMode.DOWN));
			securityWebUser.setCompletenum(RandomUtil.randomInt(10));
			securityWebUserService.insertSecurityWebUser(securityWebUser);
			logger.info(securityWebUser.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return AjaxResult.error(e.getMessage());
		}
		return AjaxResult.success();
	}

	private void checkWebUserInfo(SecurityWebUser securityWebUser) {
		//校验手机号
		if(StrUtil.isEmpty(securityWebUser.getMobile())){
			throw new ValidateException("联系电话不能为空");
		}
		if(StrUtil.isEmpty(securityWebUser.getRealname())){
			throw new ValidateException("联系人不能为空");
		}
		SecurityWebUser mobileWebUser = new SecurityWebUser();
		mobileWebUser.setMobile(securityWebUser.getMobile());
		mobileWebUser.setRoleId(4L);
		List<SecurityWebUser> mobileList = securityWebUserService.selectSecurityWebUserList(mobileWebUser);
		if(CollectionUtil.isNotEmpty(mobileList)){
			throw new ValidateException("手机号码已存在");
		}
		SecurityWebUser nameWebUser = new SecurityWebUser();
		nameWebUser.setNickname(securityWebUser.getRealname());
		nameWebUser.setRoleId(4L);
		List<SecurityWebUser> nameList = securityWebUserService.selectSecurityWebUserList(nameWebUser);
		if(CollectionUtil.isNotEmpty(nameList)){
			throw new ValidateException("用户名已存在");
		}
	}

	@PreAuthorize("@ss.hasPermi('smy:merchant:edit')")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody SecurityWebUser securityWebUser) {
		return toAjax(securityWebUserService.updateSecurityWebUser(securityWebUser));
	}

	@PreAuthorize("@ss.hasPermi('smy:user:remove')")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(securityWebUserService.deleteSecurityWebUserByIds(ids));
	}

	@PreAuthorize("@ss.hasPermi('smy:merchant:edit')")
	@Log(title = "修改状态", businessType = BusinessType.UPDATE)
	@PostMapping("/changeStatus")
	public AjaxResult changeStatus(@RequestBody OptDto optDto) {
		try {
			SecurityWebUser webUser = securityWebUserService.selectSecurityWebUserById(Long.valueOf(optDto.getOptId()));
			if(Objects.nonNull(webUser)){
				OptDto syncDto = new OptDto();
				syncDto.setOptId(webUser.getMobile());
				//存值交换
				syncDto.setOptName(optDto.getOptType());
				if(StrUtil.equals("1",optDto.getOptName())){
					syncDto.setOptType("Y");
				}else{
					syncDto.setOptType("N");
				}
				System.out.println(JSONUtil.toJsonStr(syncDto));
				String responseStr = HttpRequest.post(appBaseUrl+ LinkUrl.AUDIT_COOKER_URL).body(JSONUtil.toJsonStr(syncDto)).execute().body();
				System.out.println(responseStr);
				ResponseDto responseDto = JSONUtil.toBean(responseStr,ResponseDto.class);
				if(responseDto.isHasError()){
					throw new RuntimeException(responseDto.getMessage());
				}else{
					securityWebUserService.changeMerchantStatus(optDto.getOptId(),optDto.getOptName());
				}
			}else{
				throw new ValidateException("商家用户在系统中不存在");
			}
		} catch (Exception e) {
			AjaxResult.error(e.getMessage());
		}
		return AjaxResult.success();
	}

	@PreAuthorize("@ss.hasPermi('smy:merchant:setWineStatus')")
	@Log(title = "修改店铺铺酒状态", businessType = BusinessType.UPDATE)
	@PostMapping("/setWineStatus")
	public AjaxResult setWineStatus(@RequestBody OptDto optDto) {
		try {
			SysUser sysUser = SecurityUtils.getLoginUser().getUser();
			if(roleService.checkHaveRole(sysUser.getRoles(), UserType.QYJMS)
					|| roleService.checkHaveRole(sysUser.getRoles(), UserType.ADMIN)){
				SecurityWebUser webUser = securityWebUserService.selectSecurityWebUserById(Long.valueOf(optDto.getOptId()));
				if(Objects.nonNull(webUser)){
					webUser.setHasWine(optDto.getOptType());
					securityWebUserService.updateSecurityWebUser(webUser);
				}else{
					throw new ValidateException("商家用户在系统中不存在");
				}
			}
		} catch (Exception e) {
			AjaxResult.error(e.getMessage());
		}
		return AjaxResult.success();
	}

}
